package org.example._04_TankWar;

import java.awt.*;
import java.util.List;

public class Missile {
	private int x,y;
	private static final int XSPEED=10;
	private static final int YSPEED=10;
	
	public  static final int WIDTH=10;
	public static final int HEIGHT=10;
	
	Tank.Direction dir;
	private boolean live = true;
	private boolean good;
	
	public boolean isGood() {
		return good;
	}
	private TankClient tc;
	
	
	public Missile(int x, int y, Tank.Direction dir) {
		this.x = x;
		this.y = y;
		this.dir = dir;
	}
	public Missile (int x, int y, boolean good, Tank.Direction dir, TankClient tc)
	{
	    this(x,y,dir);
	    this.good=good;
		this.tc=tc;
	}
	
	public void draw(Graphics g)
	{
		if(!live){
			tc.missiles.remove(this);
			return;
		}
		Color c = g.getColor();
		g.setColor(Color.BLACK);
		g.fillOval(x, y, WIDTH, HEIGHT);
		g.setColor(c);
		
		move();
	}
	void move()
	{
		switch(dir){
		case L:
			x-=XSPEED;
			break;
		case LD:
			x-=XSPEED;
			y+=YSPEED;//此处是减法，不是加法，因为frame中左上方坐标是（0,0）
			break;
		case D:
			y+=YSPEED;
			break;
		case RD:
			x+=XSPEED;
			y+=YSPEED;
			break;
		case R:
			x+=XSPEED;
			break;
		case RU:
			x+=XSPEED;
			y-=YSPEED;
			break;
		case U:
			y-=XSPEED;
			break;
		case LU:
			x-=XSPEED;
			y-=XSPEED;
			break;
		}
	if(x<0 || y<0 || x > TankClient.GAME_WIDTH || y> TankClient.GAME_HEIGHT)
	{
		live = false;
		
	}
	
	}
	public boolean isLive() {
		return live;
		
	}
	public Rectangle getRect()
	{
		return new Rectangle(x,y,WIDTH,HEIGHT);
	}
	
	public boolean HitTank(Tank t)
	{
		if(this.live && this.getRect().intersects(t.getRec()) && t.isLive() && this.good != t.isGood())
		{
			if(t.isGood())
			{
				t.setLife(t.getLife()-20);
				if(t.getLife()<=0) {
					t.setLive(false);
				}
			}else{ t.setLive(false);
			}
			this.live = false;
			Explode e =new Explode(x,y,tc);
			tc.Explodes.add(e);
			return true;			
		}
		return false;
	}
	public boolean HitTanks(List<Tank> Tanks)
	{
		for(int x=0;x<Tanks.size();x++)
		{
			if(HitTank(Tanks.get(x)))
			{
				return true;
			}			
		}
		return false;
	}
	public boolean Hitwall(Wall w)
	{
		if(this.live && this.getRect().intersects(w.getRec()))
		{
			this.live=false;
			return true;
		}
		return false;
	}
}
